<template>
  <div class="pageBox">
    <!-- <div style="height:30px;">{{ currentStep }}</div> -->
    <a-row style="height:100%">
      <!-- {{ currentForm[currentTab] }} -->
      <!-- {{fApi}} -->
      <!-- {{fileList.length}} -->
      <!-- {{fileList}} -->
      <a-col
        span="8"
        style="background-color:#fff;height:85vh;border-radius:4px;padding:8px;overflow:auto;"
      >
        <Tree
          ref="tree"
          v-model="currentStep"
          :treeData="stepLists"
          :defalutData="defalutData"
          @treeClick="isShowFormChange"
          @confirmRefreshData="refreshTree"
        ></Tree>
      </a-col>
      <a-col
        v-show="Object.keys(currentStep).length && !currentStep.isStep"
        span="16"
        style="padding:8px 16px 8px 16px;height:80%;"
      >
        <div v-if="formLoading" class="example">
          <a-spin class="load" />
        </div>
        <a-tabs default-active-key="1" @change="tabsHandle">
          <a-tab-pane
            v-for="item in formLists"
            :key="item.value"
            :tab="item.label"
          >
            <div style="width:100%;padding:8px;">
              <form-create
                v-model="fApi"
                :rule="currentForm[item.value] || []"
                :option="option"
                @submit="submit"
              ></form-create>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import api from "@/server/mouldConfig.js";
import Tree from "@/components/tree/index";

const formLists = [
  {
    label: "装配",
    value: "f1"
  },
  {
    label: "自检",
    value: "f2"
  },
  {
    label: "专检",
    value: "f3"
  }
];

function createForm(lists) {
  let _lists = [];
  _lists = lists.map(item => {
    return {
      title: this.currentStep.name,
      field: this.currentStep.id,
      ...item
    };
  });
  return _lists;
}
export default {
  name: "machinePartOrderDetailIndex",
  components: {
    Tree
  },
  data() {
    return {
      currentStep: {},
      defalutData: {},
      stepLists: [],
      formLoading: false,
      currentForm: [],
      fileList: [],
      fApi: {},
      currentTab: "f1",
      formLists: formLists,
      //组件参数配置
      option: {
        form: {
          hideRequiredMark: true,
          layout: "vertical",
          labelAlign: "left",
          labelCol: {
            span: 24
          },
          wrapperCol: {
            span: 24
          }
        },
        submitBtn: {
          show: true
        },
        resetBtn: {
          show: false
        }

        //表单提交事件
        // onSubmit: function(formData) {
        //   alert(JSON.stringify(formData));
        // },
      }
    };
  },
  watch: {
    currentStep: {
      deep: true,
      handler: function(newVal) {
        let _this = this;
        // let assembly = eval("(" + newVal.assembly + ")");
        // let selfCheck = eval("(" + newVal.selfCheck + ")");
        // let specialCheck = eval("(" + newVal.specialCheck + ")");
        let formData = {
          title: this.currentStep.name,
          field: this.currentStep.id
        };
        let assembly = newVal.assembly || [];
        let selfCheck = newVal.selfCheck || [];
        let specialCheck = newVal.specialCheck || [];
        let validate = [
          {required: true, message: '输入不能为空', trigger: 'blur'}
        ]
        let props = {
          action: "https://apitest.hzncc.cn/assembly/upload/file",
          limit: 5,
          multiple: true,
          accept: "image",
          listType: "picture-card",
          onSuccess: function(file, fileList) {
            let imageList = [];
            if (fileList.length) {
              fileList.forEach(item => {
                if (item.response) {
                  imageList.push(item.response.data.url);
                } else {
                  imageList.push(item.url);
                }
              });
            }
            _this.fileList = imageList;
          },
          remove: file => {
            return new Promise((resolve, reject) => {
              this.$Modal.confirm({
                title: "确认删除图片?",
                onOk() {
                  let index = _this.fileList.indexOf(file.url);
                  if (index > -1) {
                    _this.fileList.splice(index, 1);
                  }
                  return resolve(true);
                },
                onCancel() {
                  return reject();
                }
              });
            });
          }
        };
        if (assembly.length && assembly[0]) {
          assembly = [{ ...assembly[0], ...formData }];
          assembly.forEach(item => {
            if (item.options && typeof item.options == "string") {
              item.options = eval("(" + item.options + ")");
            }
            if (item.type == "upload") {
              item.props = props;
            }else{
              item.validate = validate
            }
            if (item.type == "textarea") {
              item.props = { autoSize: { minRows: 6 } };
            }
            if (item.type == "upload" && _this.isJSON(item.value)) {
              let value = JSON.parse(item.value);
              item.value = value.fileList;
              if (this.currentTab == "f1") {
                this.fileList = value.fileList || [];
              }
            }
          });
        }
        if (selfCheck.length && selfCheck[0]) {
          selfCheck = [{ ...selfCheck[0], ...formData }];
          selfCheck.forEach(item => {
            if (item.options && typeof item.options == "string") {
              item.options = eval("(" + item.options + ")");
            }
            if (item.type == "upload") {
              item.props = props;
            }else{
              item.validate = validate
            }
            if (item.type == "textarea") {
              item.props = { autoSize: { minRows: 6 } };
            }
            if (item.type == "upload" && _this.isJSON(item.value)) {
              let value = JSON.parse(item.value);
              item.value = value.fileList;
              if (this.currentTab == "f2") {
                this.fileList = value.fileList || [];
              }
            }
          });
        }
        if (specialCheck.length && specialCheck[0]) {
          specialCheck = [{ ...specialCheck[0], ...formData }];
          specialCheck.forEach(item => {
            if (item.options && typeof item.options == "string") {
              item.options = eval("(" + item.options + ")");
            }
            if (item.type == "upload") {
              item.props = props;
            }else{
              item.validate = validate
            }
            if (item.type == "textarea") {
              item.props = { autoSize: { minRows: 6 } };
            }
            if (item.type == "upload" && _this.isJSON(item.value)) {
              let value = JSON.parse(item.value);
              item.value = value.fileList;
              if (this.currentTab == "f3") {
                this.fileList = value.fileList || [];
              }
            }
          });
        }
        this.currentForm = {
          f1: assembly || [],
          f2: selfCheck || [],
          f3: specialCheck || []
        };
      }
    }
  },
  created() {
    this.getTreeData({}, "stepLists");
  },
  methods: {
    submit(data) {
      this.formLoading = true;
      let value = "";
      if (typeof data[this.currentStep.id] == "string") {
        value = data[this.currentStep.id];
      }
      if (
        this.currentForm[this.currentTab][0].type == "upload" &&
        Array.isArray(this.fileList) &&
        this.fileList.length
      ) {
        value = JSON.stringify({ fileList: this.fileList });
      }
      let params = {
        id: this.currentStep.id,
        orderId: this.$route.query.orderId,
        forms: [
          {
            id: this.currentForm[this.currentTab][0].id,
            type: this.currentForm[this.currentTab][0].type,
            orderId: this.$route.query.orderId,
            checkType:
              this.currentTab == "f1" ? 0 : this.currentTab == "f2" ? 1 : 2,
            value: value
          }
        ]
      };
      api
        .formUpdate(params)
        .then(res => {
          if (res.code != 200) {
            this.formLoading = false;
            this.$message.error("提交失败");
            console.log(res.message);
            return;
          }
          let assList = res.data.filter(item => item.checkType == 0);
          let selfList = res.data.filter(item => item.checkType == 1);
          let specialList = res.data.filter(item => item.checkType == 2);
          this.currentStep.assembly = assList.length
            ? assList
            : this.currentStep.assembly;
          this.currentStep.selfCheck = selfList.length
            ? selfList
            : this.currentStep.selfCheck;
          this.currentStep.specialCheck = specialList.length
            ? specialList
            : this.currentStep.specialCheck;
          this.getTreeData(this.currentStep, "stepLists");
          setTimeout(() => {
            this.formLoading = false;
            this.$message.success("提交成功");
          }, 500);
        })
        .catch(err => {
          console.log(err);
          this.formLoading = false;
        });
      setTimeout(() => {
        this.formLoading = false;
      }, 1000);
    },
    isJSON(str) {
      if (typeof str == "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == "object" && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          console.log("error：" + str + "!!!" + e);
          return false;
        }
      }
    },
    isShowFormChange() {},
    refreshTree() {},
    tabsHandle(data) {
      this.currentTab = data;
      if (
        this.currentForm[data][0] &&
        this.currentForm[data][0].type == "upload"
      ) {
        this.fileList = this.currentForm[data][0].value;
      }
    },
    getTreeData(params, key) {
      api
        .findByMouldToProcess({
          mouldId: this.$route.query.mouldId,
          orderId: this.$route.query.orderId
        })
        .then(res => {
          if (res.code == 200) {
            let { data } = res;
            this.addKey(data);
            this[key] = data;
            if (Object.keys(params).length) {
              this.currentStep = params;
              this.defalutData = params;
            } else {
              this.initCurrentStep(data);
            }
          }
        });
    },
    initCurrentStep(list) {
      return list.some(item => {
        if (!item.isStep) {
          this.currentStep = item;
          this.defalutData = item;
          return true;
        } else {
          if (
            item.children &&
            Array.isArray(item.children) &&
            item.children.length
          ) {
            return this.initCurrentStep(item.children);
          } else {
            console.log("error:存在没有表单项的步骤");
            return true;
          }
        }
      });
    },
    addKey(list) {
      list.forEach(item => {
        item.scopedSlots = { icon: "icon-head", title: "orderCustom" };
        if (
          item.children &&
          Array.isArray(item.children) &&
          item.children.length
        ) {
          this.addKey(item.children);
        }
      });
    }
  }
};
</script>

<style scoped="scoped" lang="less">
.pageBox {
  padding: 16px;
  height: 100%;
  width: 100%;
}
.example {
  z-index: 1000;
  text-align: center;
  line-height: 100%;
  background: rgba(0, 0, 0, 0.034);
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  .load {
    position: absolute;
    left: 50%;
    top: 50%;
  }
}
/deep/.ant-form-item-label {
  display: flex;
  // justify-content: flex-end;
  line-height: 1.5em;
  label {
    white-space: normal;
    text-align: right;
    color: #7f7f85;
    font-weight: bolder;
    font-size: 18px;
    padding-right: 32px;
    &::after {
      content: none !important;
    }
  }
}
</style>
